package Chuong08;

import java.io.*;
import java.net.*;

public class ICQServer
{  public static void main(String[] args )
   {
     try
      {
		  // create server socket to listen at port 7777
		  ServerSocket s = new ServerSocket(7777);

         // infinite loop: server for ever
         while (true )
         {
			 // first client
			 Socket client1 = s.accept( );
	    	PrintWriter out = new PrintWriter (client1.getOutputStream());
	    	out.println(" No partner available yet. Please wait.");
	    	out.flush();

            // second client
            Socket client2 = s.accept( );

			// start a ICQ Session for the two client in a NEW thread
            new ICQSession(client1, client2).start();

            // go to begining and listen for future clients
         }
      }
      catch (Exception e)
      {  System.out.println(e);
      }
   }
}

class ICQSession extends Thread
{  public ICQSession(Socket c1, Socket c2)
   {  client1 = c1;
      client2 = c2;
   }

   public void run()
   {
	   // new thread for chanel from client 1 to client 2
		new Chanel( client1, client2).start();

		// new thread for chanel from client 2 to client 1
		new Chanel( client2, client1).start();
   }

   private Socket client1;
   private Socket client2;
}

class Chanel extends Thread
{  public Chanel(Socket f, Socket t)
   {  from = f;
      to = t;
   }

   public void run()
   {  try
      {
		  // open stream so that server can get messages from  "from"
		  // and forward them to "to"
		  BufferedReader in  = new BufferedReader
            (new InputStreamReader(from.getInputStream()));

         PrintWriter out = new PrintWriter (to.getOutputStream());

         out.println("Connection established.");
	    out.flush();

        while (true) {
			   // message from "from"
                String str = in.readLine();

              // message to "to"
                out.println(str +"\r");
                out.flush();

    		   if (str.equals("quit"))
    		   {
    		   		to.close();
    		   		from.close();
    		   		break;
			   }
         }
      }
      catch (Exception e)
      {  System.out.println(e);
      }
   }

   private Socket from;
   private Socket to;
}

